package com.tianqu.tms.www.finance.action;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.www.finance.controller.FinanceDailyReportController;
import com.tianqu.tms.www.finance.viewhelper.FinanceDailyReportViewHelper;

public class FinanceDailyReportAction  extends TmsAction {
	private Logger logger = Logger.getLogger(FinanceDailyReportAction.class);
	private static String EL = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response, UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called..version:v2");
		
		String date = uc.getParameter("date");
		String action = uc.getParameter("action");
		
		if(StringUtil.isNullOrBlank(date)) {
			date = DateUtil.DateToString11(new Date());
		}
		
		FinanceDailyReportViewHelper viewhelper = new FinanceDailyReportViewHelper();
		viewhelper.setDate(date);
		request.setAttribute(TmsConstants.VIEWHELP, viewhelper);
		
		//index
		if (StringUtil.isNullOrBlank(action)) {
			request.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			return mapping.findForward(TmsConstants.SUCCESS);
		}
		//check
		if (StringUtil.isNullOrBlank(date)) {
			setErrorsToRequest(request, TmsConstants.U0040, null); // 必须输入一个查询条件。
			return mapping.findForward(TmsConstants.SUCCESS);
		}
		
		Pattern p = Pattern.compile(EL);
		Matcher m = p.matcher(date);
		boolean dateFlag = m.matches();
		if (!dateFlag) {
			String[] param = {"对帐日期"};
			setErrorsToRequest(request, TmsConstants.U1014, param); // yyyy-MM-dd
			return mapping.findForward(TmsConstants.SUCCESS);
		}
		
		//
		FinanceDailyReportController controller = new FinanceDailyReportController();
		controller.execute(uc);
		//
		viewhelper = (FinanceDailyReportViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
		viewhelper.setDate(date);
		request.setAttribute(TmsConstants.VIEWHELP, viewhelper);
		//
		logger.debug(this.getClass().getName() + "#execute was completed.");
		return mapping.findForward(TmsConstants.SUCCESS);
	}
}
